package org.apache.rocketmq.example.quickstart;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.protocol.heartbeat.MessageModel;

import java.util.List;

/**
 * 集群模式消费者
 */
public class BroadcastConsumer_1 {
    public static void main(String[] args) throws Exception {
        // 创建消费者对象 - 指定群组
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer-group-2");
        // 指定nameServer地址
        consumer.setNamesrvAddr("39.107.66.31:9876");
        // 订阅topic
        consumer.subscribe("message-topic-3", "*");
        // 指定集群消费模式 - 默认
        consumer.setMessageModel(MessageModel.BROADCASTING);
        // 注册回调函数，处理消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> messageExtList, ConsumeConcurrentlyContext context) {
                try {
                    for (MessageExt messageExt : messageExtList) {
                        System.out.println("topic:" + messageExt.getTopic() +  ",message:" + new String(messageExt.getBody(), "UTF-8"));
                    }
                } catch (Exception e) {
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        // 启动消费者
        consumer.start();
        System.out.println("消费者已启动");
    }
}
